<template>
  <el-dialog v-model="imageDialogVisible" title="图片预览" width="50%">
    <div style="text-align: center;">
      <img :src="currentImageUrl" style="max-width: 100%; max-height: 70vh;" />
    </div>
  </el-dialog>
  
  <el-card class="main-container">
    <template #header>
      <div class="card-header">
        <span>分类结果列表</span>
      </div>
    </template>
    <!-- jw -->
    <!-- 分类统计区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <span>采血管</span>
              <el-tag type="danger">{{ wasteTypeStats['采血管'] || 0 }}</el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <span>注射器</span>
              <el-tag type="warning">{{ wasteTypeStats['注射器'] || 0 }}</el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <span>西林瓶</span>
              <el-tag type="success">{{ wasteTypeStats['西林瓶'] || 0 }}</el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <span>手套</span>
              <el-tag type="info">{{ wasteTypeStats['手套'] || 0 }}</el-tag>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <span>口罩</span>
              <el-tag type="primary">{{ wasteTypeStats['口罩'] || 0 }}</el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input 
            v-model="form.targetId" 
            placeholder="Target ID" 
            clearable 
          />
        </el-col>
        <el-col :span="8">
          <el-input 
            v-model="form.routeId" 
            placeholder="Route ID" 
            clearable 
          />
        </el-col>
        <el-col :span="8">
          <el-button 
            type="primary" 
            @click="handleClick"
          >
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      border 
      stripe
      size="default"
    >
      <el-table-column prop="log_id" label="Log ID" align="center" width="180">
        <template #default="{ row }">
          {{ row.log_id ? row.log_id.toString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" width="100">
        <template #default="{ row }">
          <img
            style="width: 50px; height: 50px; cursor: pointer; object-fit: cover; border-radius: 4px;"
            :src="getImageUrl(row.log_id)"
            @click="openImageDialog(row.log_id)"
            @error="handleImageError"
          />
        </template>
      </el-table-column>
      <el-table-column label="分类时间" align="center" width="180">
        <template #default="{ row }">
          {{ formatDate(row.recognitionTime) }}
        </template>
      </el-table-column>
      <el-table-column label="采血管" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.sort_result_name === '采血管' ? '#F56C6C' : '' }">
            {{ getScoreByName(row, '采血管') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="注射器" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.sort_result_name === '注射器' ? '#F56C6C' : '' }">
            {{ getScoreByName(row, '注射器') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="西林瓶" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.sort_result_name === '西林瓶' ? '#F56C6C' : '' }">
            {{ getScoreByName(row, '西林瓶') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="手套" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.sort_result_name === '手套' ? '#F56C6C' : '' }">
            {{ getScoreByName(row, '手套') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="口罩" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.sort_result_name === '口罩' ? '#F56C6C' : '' }">
            {{ getScoreByName(row, '口罩') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="分类结果" align="center">
        <template #default="{ row }">
          <span>{{ row.sort_result_name }}</span>
          <el-tag 
            type="danger" 
            size="small" 
            style="margin-left: 8px"
          >
            {{ getScoreByName(row, row.sort_result_name) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="4">
          <div class="info-item">
            <span>总条数：</span>
            <el-tag>{{ form.totalElements }}</el-tag>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="info-item">
            <span>总页数：</span>
            <el-tag>{{ form.totalPages }}</el-tag>
          </div>
        </el-col>
        <el-col :span="10">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="form.size"
            :page-sizes="[5, 10, 20, 50]"
            :total="form.totalElements"
            layout="sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
        <el-col :span="6">
          <div class="jump-page">
            <el-input
              v-model="jumpPage"
              placeholder="页码"
              style="width: 100px"
              @keyup.enter="handleJumpPage"
            >
              <template #append>
                <el-button @click="handleJumpPage">
                  跳转
                </el-button>
              </template>
            </el-input>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script>
import { onActivated, onMounted, reactive, ref } from "vue"
import AxiosInstance from "../utils/axios-instance"
import api from "../api/api"
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus'

export default {
  name: "easydl-page",
  setup() {
    const form = reactive({
      totalElements: 0,
      totalPages: 0,
      size: 20,
      page: 0,
      targetId: '',
      routeId: '', // 路线id
      id: '' 
    })

    const currentPage = ref(1)
    const tableData = ref([])
    const jumpPage = ref('')
    const wasteTypeStats = ref({})
    const imageDialogVisible = ref(false)
    const currentImageUrl = ref('')

    // 根据名称获取分数
    const getScoreByName = (row, name) => {
      const result = row.results.find(r => r.name === name)
      return result ? (result.score * 100).toFixed(2) + '%' : '0%'
    }

    // 获取废物类型统计数据
    async function fetchWasteTypeStats() {
      try {
        const response = await api.getWasteTypeStatistics()
        console.log('Waste Type Stats Response:', response)
        wasteTypeStats.value = response || {}
      } catch (error) {
        console.error('获取废物类型统计数据失败:', error)
        ElMessage.error('获取废物类型统计数据失败: ' + (error.message || '未知错误'))
        wasteTypeStats.value = {}
      }
    }

    async function handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 使用新的删除API删除分类结果及其图片
        await AxiosInstance.delete(`/api/classification/result/${row.easyDlResultId}`)
        ElMessage.success('删除成功')
        handleClick()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }
    }

    async function handleClick() {
      try {
        // 加载表格数据
        const response = await api.getEasyDlResults(
          form.targetId || null,
          form.page,
          form.size,
          form.id
        )
        console.log('API Response:', response);
        if (response && response._embedded && response._embedded.easyDlResults) {
          form.totalElements = response.page.totalElements
          form.totalPages = response.page.totalPages
          
          // 确保log_id被处理为字符串
          let processedData = response._embedded.easyDlResults.map(item => {
            // 确保log_id是字符串类型
            if (item.log_id !== undefined) {
              item.log_id = String(item.log_id);
              console.log('处理表格项log_id:', item.log_id);
            }
            return item;
          });
          
          // 按照分类时间降序排序，最新的排在最前面
          processedData.sort((a, b) => {
            // 确保有recognitionTime字段
            if (!a.recognitionTime && !b.recognitionTime) return 0;
            if (!a.recognitionTime) return 1;  // a没有时间，排在后面
            if (!b.recognitionTime) return -1; // b没有时间，排在后面
            
            // 打印出日期字符串和转换后的时间戳，用于调试
            const dateA = new Date(a.recognitionTime);
            const dateB = new Date(b.recognitionTime);
            const timeA = dateA.getTime();
            const timeB = dateB.getTime();
            
            console.log(`排序比较: ${a.log_id} 时间: ${a.recognitionTime} -> ${dateA} (${timeA})`);
            console.log(`排序比较: ${b.log_id} 时间: ${b.recognitionTime} -> ${dateB} (${timeB})`);
            console.log(`排序结果: ${timeB - timeA > 0 ? 'b更新' : 'a更新'}, 差值: ${timeB - timeA}`);
            
            // 降序排列，最新的在前
            return timeB - timeA;
          });
          
          // 打印排序后的结果
          console.log('排序后数据顺序:');
          processedData.forEach((item, index) => {
            console.log(`[${index}] ${item.log_id}, 时间: ${item.recognitionTime}`);
          });
          
          tableData.value = processedData;
          console.log('Loaded, sorted and processed data:', tableData.value);
        } else {
          console.warn('No data in response:', response);
          tableData.value = [];
          form.totalElements = 0;
          form.totalPages = 0;
          currentPage.value = 1;
        }
        
        // 刷新废物类型统计数据
        await fetchWasteTypeStats()
      } catch (error) {
        console.error('API Error:', error);
        ElMessage.error('获取数据失败: ' + (error.message || '未知错误'))
        tableData.value = [];
        form.totalElements = 0;
        form.totalPages = 0;
        currentPage.value = 1;
      }
    }

    onActivated(() => {
      console.log('Component activated, loading data...');
      handleClick()
    })

    onMounted(() => {
      console.log('Component mounted, loading data...');
      handleClick()
    })

    const handleSizeChange = (val) => {
      form.size = val
      currentPage.value = 1
      form.page = 0
      handleClick()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      form.page = val - 1
      handleClick()
    }

    const handleJumpPage = () => {
      const page = parseInt(jumpPage.value)
      if (isNaN(page) || page < 1 || page > form.totalPages) {
        ElMessage.warning(`请输入1-${form.totalPages}之间的页码`)
        return
      }
      currentPage.value = page
      form.page = page - 1
      handleClick()
      jumpPage.value = ''
    }

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }

    // 获取图片URL
    const getImageUrl = (logId) => {
      // 确保logId是字符串
      const stringLogId = String(logId);
      console.log('getImageUrl - 原始logId:', logId);
      console.log('getImageUrl - 处理后stringLogId:', stringLogId);
      return api.getClassificationImage(stringLogId)
    }

    // 打开图片对话框
    const openImageDialog = (logId) => {
      // 确保logId是字符串
      const stringLogId = String(logId);
      console.log('openImageDialog - 原始logId:', logId);
      console.log('openImageDialog - 处理后stringLogId:', stringLogId);
      currentImageUrl.value = getImageUrl(stringLogId)
      imageDialogVisible.value = true
    }

    // 处理图片加载错误
    const handleImageError = (e) => {
      console.error('图片加载失败:', e)
      ElMessage.error('图片加载失败')
    }

    return {
      form,
      tableData,
      currentPage,
      handleClick,
      handleDelete,
      getScoreByName,
      handleSizeChange,
      handleCurrentChange,
      jumpPage,
      handleJumpPage,
      wasteTypeStats,
      formatDate,
      getImageUrl,
      handleImageError,
      imageDialogVisible,
      currentImageUrl,
      openImageDialog
    }
  }
}
</script>

<style scoped>
.main-container {
  margin: 20px;
}

.card-header {
  font-weight: bold;
}

.filter-section {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.jump-page {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f5f7fa;
}

:deep(.el-table .cell) {
  padding: 8px;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 100%;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

:deep(.stats-card .el-card__body) {
  padding: 12px;
}

:deep(.el-tag) {
  font-size: 16px;
  padding: 4px 12px;
}

:deep(.el-image) {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

:deep(.el-image:hover) {
  transform: scale(1.05);
}
</style>